package liuyang.bigeventserver.modules.security.jwt.impl;

import cn.hutool.aop.interceptor.SpringCglibInterceptor;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import liuyang.bigeventserver.modules.security.jwt.JwtTokenService;
import liuyang.bigeventserver.modules.security.jwt.JwtTokenServiceProperties;
import liuyang.bigeventserver.modules.security.jwt.vo.PrincipalInfo;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.crypto.SecretKey;
import java.util.Date;

/**
 * 文摘：
 * https://blog.csdn.net/qq_50969362/article/details/134100542
 * 工具：
 * https://jwt.io/
 *
 * @author xconf
 * @since 2024/2/28
 */
//@Service
@Slf4j
public class JJwtTokenService implements JwtTokenService {

    private final JwtTokenServiceProperties jwtTokenServiceProperties;
    private final SecretKey KEY;

    public JJwtTokenService(JwtTokenServiceProperties jwtTokenServiceProperties) {
        this.jwtTokenServiceProperties = jwtTokenServiceProperties;
        KEY = Keys.hmacShaKeyFor(jwtTokenServiceProperties.getSecretKey().getBytes());
    }

    @Override
    public String getSecretKey() {
        return jwtTokenServiceProperties.getSecretKey();
    }

    @Override
    public String getIssuer() {
        return jwtTokenServiceProperties.getIssuer();
    }

    @Override
    public Long getTtl() {
        return jwtTokenServiceProperties.getTtl();
    }

    @Override
    public String sign(String username) {
        return sign(username, username);
    }

    @Override
    public String sign(String userid, String username) {
        final String token = Jwts.builder()
                //.setId(jti)
                .setId(userid)// 这个jjwt的就先占用jti吧
                .setSubject(username)
                .setIssuer(jwtTokenServiceProperties.getIssuer())
                .setExpiration(new Date(System.currentTimeMillis() + jwtTokenServiceProperties.getTtl()))
                .signWith(KEY, SignatureAlgorithm.HS256) // 设置签名， 使用SECRET_KEY
                .compact();
        log.debug("jwt = {}", token);
        return token;
    }

    @Override
    public PrincipalInfo verify(String token) {
        // TODO
        PrincipalInfo info = new PrincipalInfo();
        Claims claims = Jwts.parser()
                .verifyWith(KEY)
                .build()
                .parseSignedClaims(token)
                .getBody();
        info.setId(claims.getId());             // jti
        info.setSubject(claims.getSubject());   // sub
        return info;
    }
}
